<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Log;

class Index extends Common
{
    public function index()
    {
        // 供应商人数
        $supplier_count = Db::name('user_ident')->where(['status' => 1, 'type' => 1])->count();
        // 渠道商人数
        $channel_count = Db::name('user_ident')->where(['status' => 1, 'type' => 2])->count();
        // 业务员人数
        $salesman_count = Db::name('user_ident')->where(['status' => 1, 'type' => 3])->count();
        // 游客人数
        $visitor_count = Db::name('user')->where(['is_admin' => 0, 'supplier_status' => ['neq', 2], 'channel_status' => ['neq', 2], 'salesman_status' => ['neq', 2]])->count();

        // 饼图数据
        $pie_data = [
            [
                'name' => '供应商人数',
                'value' => $supplier_count
            ],
            [
                'name' => '渠道商人数',
                'value' => $channel_count
            ],
            [
                'name' => '业务员人数',
                'value' => $salesman_count
            ],
            [
                'name' => '游客人数',
                'value' => $visitor_count
            ]
        ];
        $this->assign('pie_data', json_encode($pie_data, JSON_UNESCAPED_UNICODE));

        // 柱状图数据
        $salesman_list = Db::name('user_ident')->field('id,user_id,username')->where(['status' => 1, 'type' => 3])->select();
        $bar_x = [];
        $bar_y = [];
        if ($salesman_list) {
            foreach ($salesman_list as $v) {
                $bar_x[] = $v['username'];

                $son_count = Db::name('user')->where(['up_salesman_user_id' => $v['user_id']])->count();
                $bar_y[] = $son_count;
            }
        }
        $this->assign('bar_x', json_encode($bar_x, JSON_UNESCAPED_UNICODE));
        $this->assign('bar_y', json_encode($bar_y, JSON_UNESCAPED_UNICODE));

        // 折线图数据
        $time_list = Db::name('user')
            ->field('DISTINCT DATE_FORMAT(FROM_UNIXTIME(create_time), "%Y-%m-%d") as formatted_create_time')
            ->select();
        $line_x = [];
        $line_y = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $date = $v['formatted_create_time'];
                $line_x[] = $date;

                $start_time = strtotime($date);
                $end_time = strtotime($date) + 86399;
                $count = Db::name('user')->whereBetween('create_time', [$start_time, $end_time])->count();
                $line_y[] = $count;
            }
        }
        $this->assign('line_x', json_encode($line_x, JSON_UNESCAPED_UNICODE));
        $this->assign('line_y', json_encode($line_y, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '统计');
        return $this->fetch();
    }

}
